import UserEmojiStore from "@/store/user-emoji";
import {
    getEmojiPackageItems,
    insertEmojiPackageItem,
    deleteEmojiPackageItem,
    getUserEmojiPackage,
    createUserEmojiPackage,
    updateUserEmojiPackage,
    updateEmojiPackageItem,
    getEmojiPackageItemById,
} from "@/services/sqlite/user-emoji";
import CurrentUserIdManager from "@/utils/user-utils";
import {UserEmojiPackItemCreateType, EmojiPackItemUpdateType, EmojiPackItemUpdateRequest} from "@/types/user-emoji";
import {
    updateEmojiItemApi,
    uploadEmojiPackApi,
    getUserEmojisApi,
    deleteEmojiItemApi,
    getUserEmojiPackApi
} from "@/services/api/user-emoji";
import {ResponseCode} from "@/types/api-common";
import AlertService from "@/components/Global/Alert/service"
import {cacheEmoji, removeCacheEmoji} from "@/utils/file-utils";

export const useEmojiState = () => UserEmojiStore(state => state.state);

export const useEmojiActions = () => {
    const actions = UserEmojiStore(state => state.actions);
    const userId = CurrentUserIdManager.getUserId()

    const checkOrUpdateEmojiItems = async () => {
        const resp = await getUserEmojiPackApi()
        if (resp.data.code === ResponseCode.SUCCESS) {
            const userEmojiPack = await getUserEmojiPackage(userId)
            if (!userEmojiPack && resp.data.data) {
                await createUserEmojiPackage({createTime: resp.data.data.createTime, ownerId: userId, updateTime: resp.data.data.updateTime});
                await fetchEmojiItems(true);
                return;
            } else {
                if (String(userEmojiPack.updateTime) !== String(resp.data.data.updateTime)) {
                    // 如果本地的更新时间和服务器不一致，重新获取表情包
                    await updateUserEmojiPackage({createTime: resp.data.data.createTime, ownerId: userId, updateTime: resp.data.data.updateTime});
                    await fetchEmojiItems(true);
                    return;
                }
            }
        }
        await fetchEmojiItems();
    }

    const fetchEmojiItems = async (syncApi: boolean = false) => {
        actions.setLoading(true);
        try {
            let items = await getEmojiPackageItems(userId);
            if (syncApi) {
                const resp = await getUserEmojisApi()
                if (resp.data.code === ResponseCode.SUCCESS) {
                    const serverItems = resp.data.data;
                    if (serverItems.length > 0) {
                        // 如果API返回的表情包项不为空，更新本地缓存
                        for (const localItem of items) {
                            const serverItem = serverItems.find((item) => item.id === localItem.id);
                            if (serverItem) {
                                if (Number(serverItem.updateTime) !== localItem.updateTime) {
                                    // 更新本地项
                                    items = items.map((item) => {
                                        if (item.id === localItem.id) {
                                            return {
                                                ...item,
                                                sortOrder: serverItem.sortOrder,
                                                updateTime: serverItem.updateTime,
                                                createTime: serverItem.createTime,
                                            };
                                        }
                                        return item;
                                    });
                                    await updateEmojiPackageItem({
                                        id: localItem.id,
                                        sortOrder: serverItem.sortOrder,
                                        updateTime: serverItem.updateTime,
                                        createTime: serverItem.createTime,
                                    });
                                }
                            }
                        }

                        // 添加新的表情包项
                        for (const serverItem of serverItems) {
                            const localItem = items.find((item) => item.id === serverItem.id);
                            if (!localItem) {
                                // 如果本地没有该项，添加到本地
                                const filePath = await cacheEmoji(serverItem.fileUrl)
                                if (filePath) {
                                    items.push({filePath, serverUrl: serverItem.fileUrl, ...serverItem})
                                    await insertEmojiPackageItem({...serverItem, userId, filePath, serverUrl: serverItem.fileUrl, fileId: serverItem.fileId});
                                }
                            }
                        }

                        // 删除不一致的表情包项
                        const deletedItems = items.filter((item) => !serverItems.some((serverItem) => serverItem.id === item.id));
                        items = items.filter((item) => serverItems.some((serverItem) => serverItem.id === item.id));
                        for (const deletedItem of deletedItems) {
                            await deleteEmojiPackageItem(deletedItem.id, userId);
                            await removeCacheEmoji(deletedItem.filePath); // 删除本地缓存文件
                            actions.deleteEmojiItem(deletedItem.id); // 本地删除
                        }
                    }
                }
            }
            actions.setEmojiItems(items || []);
        } catch (error) {
            console.error("Failed to fetch emoji items:", error);
        } finally {
            actions.setLoading(false);
        }
    };

    const addEmojiItem = async (formData: FormData) => {
        actions.setLoading(true);
        try {
            const resp = await uploadEmojiPackApi(formData) // 远程更新
            const emojiData = resp.data.data
            if (resp.data.code === ResponseCode.SUCCESS) {
                // 缓存
                const filePath = await cacheEmoji(emojiData.fileUrl)
                if (filePath) {
                    const item : UserEmojiPackItemCreateType = {
                        id: emojiData.emojiId,
                        fileId: emojiData.fileId,
                        fileUrl: emojiData.fileUrl,
                        filePath,
                        serverUrl: emojiData.fileUrl,
                        sortOrder: 0,
                        createTime: emojiData.emojiCreateTime,
                        updateTime: emojiData.emojiUpdateTime,
                        userId
                    }
                    actions.addEmojiItem(item); // 本地更新
                    await insertEmojiPackageItem(item);
                } else {
                    AlertService.showAlert('error', "添加表情包失败，无法缓存文件");
                    return;
                }
            } else {
                AlertService.showAlert('error', "添加表情包失败");
            }
        } catch (error) {
            console.error("Failed to add emoji item:", error);
        } finally {
            actions.setLoading(false);
        }
    };

    const updateEmojiItem = async (update: EmojiPackItemUpdateRequest) => {
        actions.setLoading(true);
        try {
            const resp = await updateEmojiItemApi(update);
            if (resp.data.code === ResponseCode.SUCCESS) {
                const emoji : EmojiPackItemUpdateType = {...update,
                    createTime: resp.data.data.emojiCreateTime,
                    updateTime: resp.data.data.emojiUpdateTime,
                };
                await updateEmojiPackageItem(emoji);
                actions.updateEmojiItem(emoji);
                actions.sortEmojiItems(); // 排序
            } else {
                AlertService.showAlert('error', "添加表情包失败");
            }
        } catch (error) {
            console.error("Failed to add emoji item:", error);
        } finally {
            actions.setLoading(false);
        }
    };

    const deleteEmojiItem = async (itemId: string) => {
        actions.setLoading(true);
        try {
            const resp = await deleteEmojiItemApi(itemId); // 远程删除
            if (resp.data.code === ResponseCode.SUCCESS) {
                const emoji = await getEmojiPackageItemById(itemId, userId); // 更新用户表情包
                if (emoji) {
                    await deleteEmojiPackageItem(itemId, userId);
                    actions.deleteEmojiItem(itemId);
                    await removeCacheEmoji(emoji.filePath); // 删除本地缓存文件
                }
                AlertService.showAlert('success', "删除表情包成功");
            }
        } catch (error) {
            console.error("Failed to delete emoji item:", error);
            AlertService.showAlert('error', "删除表情包失败");
        } finally {
            actions.setLoading(false);
        }
    };

    return {
        checkOrUpdateEmojiItems,
        addEmojiItem,
        fetchEmojiItems,
        updateEmojiItem,
        deleteEmojiItem,
    };
};